#!/usr/bin/env python3
"""日期时间处理的工具类
"""

import time
import datetime
import chinese_calendar
from functools import wraps


def sleep(seconds=0.5):
  """
  睡眠时间
  """
  time.sleep(seconds)

def now():
  '''当前时间戳'''
  return int(time.time())

def timestamp():
  """时间戳"""
  return time.time()

def makeTimestamp(year=datetime.datetime.now().year,month=datetime.datetime.now().month,day=datetime.datetime.now().day,hour=0,minute=0,second=0):
    t=datetime.datetime(year, month, day, hour, minute, second).timestamp()
    return int(t)

def todayTimestamp():
  """获取当天零点的时间戳

  Returns:
    int: 当天零点的时间戳，精确到秒
  """
  return int(time.mktime(datetime.date.today().timetuple()))


# def timestamps(ctime=None, level='s'):
#   """获取时间戳(int)
#
#   Args:
#       ctime (float, optional): 指定时间. Defaults to 当前时间.
#       level (str, optional): 精确等级, s - 精确到秒, ms - 精确到毫秒. Defaults to 's'.
#
#   Returns:
#       int: 10/13位的时间戳数字
#   """
#   if ctime is None:
#     ctime = time.time()
#   if level == 'ms':
#     return int(round(ctime * 1000))
#   else:
#     return int(ctime)


def format(pattern="%Y-%m-%d %H:%M:%S",timestamp=now()):
  """将时间戳格式化为指定格式的字符串形式

  Args:
      pattern (str, optional): 待格式化的形式. 默认: '%Y-%m-%d %H:%M:%S'.
      timestamps (float, optional): 时间戳，默认当前时间戳

  Returns:
      str: 正确格式化后的日期字符串
  """
  timeArray = time.localtime(timestamp)
  return time.strftime(pattern, timeArray)

def to_timestamps(s,pattern):
  return int(time.mktime(time.strptime(s,pattern)))

def is_trading_day(timestamp=todayTimestamp()):
  date=datetime.datetime.fromtimestamp(timestamp)
  if date.isoweekday()<=5 and chinese_calendar.is_workday(date):
    return True
  else:
    return False

def is_trading_time(timestamp=now()):
  dt = datetime.datetime.fromtimestamp(timestamp)
  if (dt.time() > datetime.time(hour=9, minute=30) and dt.time() < datetime.time(hour=15)) and is_trading_day(timestamp):
    return True
  return False

def is_after_open(timestamp=now()):
  dt = datetime.datetime.fromtimestamp(timestamp)
  if is_trading_day(timestamp) and dt.time() >= datetime.time(hour=9, minute=30):
    return True
  return False

def is_before_open(timestamp=now()):
  dt = datetime.datetime.fromtimestamp(timestamp)
  if is_trading_day(timestamp) and dt.time() < datetime.time(hour=9, minute=30):
    return True
  return False

def is_before_close(timestamp=now()):
  dt = datetime.datetime.fromtimestamp(timestamp)
  if is_trading_day(timestamp) and dt.time() < datetime.time(hour=15):
    return True
  return False

def is_after_close(timestamp=now()):
  dt = datetime.datetime.fromtimestamp(timestamp)
  if is_trading_day(timestamp) and dt.time() >= datetime.time(hour=15):
    return True
  return False

def previous_trading_day(timstamp=todayTimestamp()):
    timstamp-=86400
    if is_trading_day(timstamp):
      return timstamp
    else:
      return previous_trading_day(timstamp)


def next_trading_day(timstamp=todayTimestamp()):
  timstamp += 86400
  if is_trading_day(timstamp):
    return timstamp
  else:
    return next_trading_day(timstamp)

def previous_no_trade_day(timstamp=todayTimestamp()):
  timstamp -= 86400
  if is_trading_day(timstamp):
    return previous_no_trade_day(timstamp)
  else:
    return timstamp


def get_trading_days(stimestamp,etimestamp=todayTimestamp()):
  t=stimestamp
  tradingDays=[]
  while t<=etimestamp:
    if is_trading_day(t):
      tradingDays.append(int(t))
    t += 86400
  return tradingDays

def get_latest_trade_day(mode='ts'):
    '''返回最近一个交易日'''
    todayt = todayTimestamp()
    if is_trading_day(todayt):
      latest = todayt
    else:
      latest =previous_trading_day(todayt)
    if mode == 'ts':
      return latest
    return format('%Y-%m-%d', latest)


def running_time(func):
  """函数运行时间"""

  @wraps(func)
  def wrapper(*args, **kwargs):
    start = time.time()
    res = func(*args, **kwargs)
    print("Done！用时%.3f秒！" % (timestamp() - start))
    return res

  return wrapper


if __name__ == '__main__':
  r=previous_no_trade_day()
  print(is_close())